<template>
  <div class="student-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>课题浏览与申请</h1>
      <p>浏览企业发布的课题，选择感兴趣的进行申请</p>
    </div>

    <!-- 功能导航 -->
    <el-tabs v-model="activeTab" class="student-tabs">
      <el-tab-pane label="课题浏览" name="topics">
        <!-- 筛选条件 -->
        <div class="filter-section">
          <el-card class="filter-card">
            <div class="filter-row">
              <el-input
                v-model="filters.keyword"
                placeholder="输入关键词搜索课题"
                clearable
                style="width: 300px"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>

              <el-select
                v-model="filters.category"
                placeholder="选择分类"
                clearable
                style="width: 200px"
              >
                <el-option label="计算机科学" value="computer_science" />
                <el-option label="电子信息" value="electronics" />
                <el-option label="机械工程" value="mechanical" />
                <el-option label="化学化工" value="chemistry" />
                <el-option label="生物医学" value="biomedical" />
                <el-option label="经济管理" value="economics" />
                <el-option label="其他" value="other" />
              </el-select>

              <el-select
                v-model="filters.status"
                placeholder="选择状态"
                clearable
                style="width: 200px"
              >
                <el-option label="开放" value="open" />
                <el-option label="已关闭" value="closed" />
                <el-option label="进行中" value="in_progress" />
                <el-option label="已完成" value="completed" />
              </el-select>

              <el-input-number
                v-model="filters.budget_min"
                placeholder="最小预算"
                :min="0"
                :step="1000"
                style="width: 150px"
              />

              <el-input-number
                v-model="filters.budget_max"
                placeholder="最大预算"
                :min="0"
                :step="1000"
                style="width: 150px"
              />

              <el-select
                v-model="filters.is_public"
                placeholder="是否公开"
                clearable
                style="width: 150px"
              >
                <el-option label="公开" value="true" />
                <el-option label="不公开" value="false" />
              </el-select>

              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>

              <el-button @click="resetFilters">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </div>
          </el-card>
        </div>

        <!-- 课题列表 -->
        <div class="topics-section">
          <!-- 空状态 -->
          <div v-if="filteredTopics.length === 0" class="empty-state">
            <el-empty description="暂无课题数据">
              <el-button type="primary" @click="loadProjects">刷新数据</el-button>
            </el-empty>
          </div>
          
          <!-- 课题列表 -->
          <el-row v-else :gutter="20">
            <el-col
              v-for="topic in filteredTopics"
              :key="topic.id"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
            >
              <el-card class="topic-card" shadow="hover">
                <div class="topic-header">
                  <h3 class="topic-title">{{ topic.title }}</h3>
                  <el-tag :type="getStatusType(topic.status)" size="small">
                    {{ topic.statusText }}
                  </el-tag>
                </div>

                <div class="topic-content">
                  <p class="topic-description">{{ topic.description }}</p>

                  <div class="topic-info">
                    <div class="info-item">
                      <el-icon><OfficeBuilding /></el-icon>
                      <span>{{ topic.enterprise }}</span>
                    </div>
                    <div class="info-item">
                      <el-icon><Collection /></el-icon>
                      <span>{{ topic.category }}</span>
                    </div>
                    <div class="info-item">
                      <el-icon><Money /></el-icon>
                      <span>{{ topic.budget || '面议' }}</span>
                    </div>
                  </div>

                  <div class="topic-requirements">
                    <h4>要求：</h4>
                    <ul>
                      <li v-for="(req, index) in getRequirementsList(topic.requirements)" :key="index">{{ req }}</li>
                    </ul>
                  </div>
                </div>

                <div class="topic-actions">
                  <el-button
                    type="primary"
                    @click="showApplyDialog(topic)"
                    :disabled="topic.hasApplied"
                  >
                    {{ topic.hasApplied ? '已申请' : '申请课题' }}
                  </el-button>

                  <el-button @click="showTopicDetail(topic)">
                    查看详情
                  </el-button>

                  <el-button 
                    type="success" 
                    @click="contactEnterprise(topic)"
                    :icon="ChatDotRound"
                  >
                    联系企业
                  </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 分页 -->
          <div class="pagination-wrapper">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[12, 24, 36, 48]"
              :total="totalTopics"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="我的申请" name="applications">
        <div class="applications-section">
          <el-card class="applications-card">
            <template #header>
              <div class="card-header">
                <span>申请记录</span>
                <el-select v-model="applicationStatus" placeholder="筛选状态" style="width: 150px">
                  <el-option label="全部" value="" />
                  <el-option label="待审核" value="pending" />
                  <el-option label="已通过" value="accepted" />
                  <el-option label="已拒绝" value="rejected" />
                  <el-option label="已撤回" value="withdrawn" />
                </el-select>
              </div>
            </template>

            <el-table :data="filteredApplications" style="width: 100%">
              <el-table-column prop="topicTitle" label="课题名称" />
              <el-table-column prop="enterprise" label="企业名称" width="150" />
              <el-table-column prop="applyTime" label="申请时间" width="120" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getApplicationStatusType(scope.row.status)">
                    {{ scope.row.statusText }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="feedback" label="反馈意见" />
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button size="small" @click="viewApplicationDetail(scope.row)">
                    查看详情
                  </el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="withdrawApplication(scope.row)"
                    v-if="scope.row.status === 'pending'"
                  >
                    撤回
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>
      </el-tab-pane>

      <el-tab-pane label="我的课题" name="projects">
        <div class="projects-section">
          <el-card class="projects-card">
            <template #header>
              <div class="card-header">
                <span>我的课题</span>
              </div>
            </template>

            <el-row :gutter="20">
              <el-col
                v-for="project in myProjects"
                :key="project.id"
                :xs="24"
                :sm="12"
                :md="8"
              >
                <el-card class="project-card" shadow="hover">
                  <div class="project-header">
                    <h3 class="project-title">{{ project.title }}</h3>
                    <el-tag :type="getProjectStatusType(project.status)" size="small">
                      {{ project.statusText }}
                    </el-tag>
                  </div>

                  <div class="project-content">
                    <p class="project-description">{{ project.description }}</p>

                    <div class="project-info">
                      <div class="info-item">
                        <el-icon><OfficeBuilding /></el-icon>
                        <span>{{ project.enterprise }}</span>
                      </div>
                      <div class="info-item">
                        <el-icon><User /></el-icon>
                        <span>导师：{{ project.mentor }}</span>
                      </div>
                      <div class="info-item">
                        <el-icon><Calendar /></el-icon>
                        <span>开始：{{ project.startDate }}</span>
                      </div>
                      <div class="info-item">
                        <el-icon><Timer /></el-icon>
                        <span>进度：{{ project.progress }}%</span>
                      </div>
                    </div>
                  </div>

                  <div class="project-actions">
                    <el-button type="primary" @click="viewProjectDetail(project)">
                      查看详情
                    </el-button>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-card>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="简历管理" name="resume">
        <ResumeBuilder />
      </el-tab-pane>
    </el-tabs>

    <!-- 申请课题对话框 -->
    <el-dialog
      v-model="applyDialogVisible"
      title="申请课题"
      width="700px"
      :before-close="handleCloseApplyDialog"
    >
      <el-form
        :model="applyForm"
        :rules="applyRules"
        ref="applyFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-form-item label="课题名称">
          <el-input :model-value="currentTopic?.title || ''" disabled />
        </el-form-item>

        <el-form-item label="企业名称">
          <el-input :model-value="currentTopic?.enterprise || ''" disabled />
        </el-form-item>

        <el-form-item label="申请信" prop="coverLetter">
          <el-input
            v-model="applyForm.coverLetter"
            type="textarea"
            :rows="4"
            placeholder="请简要描述你的申请动机和相关经验..."
          />
        </el-form-item>

        <el-form-item label="研究计划" prop="researchPlan">
          <el-input
            v-model="applyForm.researchPlan"
            type="textarea"
            :rows="4"
            placeholder="请简要描述你的研究计划..."
          />
        </el-form-item>

        <el-form-item label="申请动机" prop="motivation">
          <el-input
            v-model="applyForm.motivation"
            type="textarea"
            :rows="2"
            placeholder="请简要描述你的申请动机..."
          />
        </el-form-item>

        <el-form-item label="资质说明" prop="qualifications">
          <el-input
            v-model="applyForm.qualifications"
            type="textarea"
            :rows="2"
            placeholder="请简要描述你的相关资质..."
          />
        </el-form-item>

        <el-form-item label="预期投入时间(小时/周)" prop="expectedTime">
          <el-input-number
            v-model="applyForm.expectedTime"
            :min="1"
            :max="40"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="可开始时间" prop="startDate">
          <el-date-picker
            v-model="applyForm.startDate"
            type="date"
            placeholder="选择可开始日期"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="可结束时间" prop="endDate">
          <el-date-picker
            v-model="applyForm.endDate"
            type="date"
            placeholder="选择可结束日期"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="作品集链接" prop="portfolio">
          <el-input v-model="applyForm.portfolio" placeholder="请输入作品集链接" />
        </el-form-item>

        <el-form-item label="简历链接" prop="resume">
          <el-input v-model="applyForm.resume" placeholder="请输入简历链接" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="applyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitApplication">提交申请</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 课题详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="课题详情"
      width="800px"
    >
      <div v-if="currentTopic" class="topic-detail">
        <h2>{{ currentTopic.title }}</h2>
        <p class="detail-description">{{ currentTopic.description }}</p>

        <el-descriptions :column="2" border>
          <el-descriptions-item label="企业名称">{{ currentTopic.enterprise || '未知企业' }}</el-descriptions-item>
          <el-descriptions-item label="课题分类">{{ currentTopic.category }}</el-descriptions-item>
          <el-descriptions-item label="预算">{{ currentTopic.budget || '面议' }}元</el-descriptions-item>
          <el-descriptions-item label="截止日期">{{ formatDate(currentTopic.deadline) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentTopic.status)">
              {{ currentTopic.statusText }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="是否公开">
            <el-tag :type="currentTopic.is_public ? 'success' : 'warning'">
              {{ currentTopic.is_public ? '公开' : '私有' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="浏览次数">{{ currentTopic.view_count || 0 }}</el-descriptions-item>
          <el-descriptions-item label="申请次数">{{ currentTopic.apply_count || 0 }}</el-descriptions-item>
          <el-descriptions-item label="发布时间">{{ currentTopic.publishTime }}</el-descriptions-item>
        </el-descriptions>

        <div class="detail-section">
          <h3>具体要求</h3>
          <div class="requirements-list">
            <p v-for="(req, index) in getRequirementsList(currentTopic.requirements)" :key="index">
              {{ index + 1 }}. {{ req }}
            </p>
          </div>
        </div>

        <div class="detail-section" v-if="currentTopic.tags">
          <h3>标签</h3>
          <div class="tags-container">
            <el-tag v-for="tag in currentTopic.tags.split(',')" :key="tag" class="tag-item">
              {{ tag.trim() }}
            </el-tag>
          </div>
        </div>

        <div class="detail-section" v-if="currentTopic.contact_info">
          <h3>联系方式</h3>
          <p>{{ currentTopic.contact_info }}</p>
        </div>

        <div class="detail-section" v-if="currentTopic.skills">
          <h3>技能要求</h3>
          <p>{{ currentTopic.skills }}</p>
        </div>

        <div class="detail-section" v-if="currentTopic.location">
          <h3>工作地点</h3>
          <p>{{ currentTopic.location }}</p>
        </div>

        <div class="detail-section" v-if="currentTopic.duration">
          <h3>项目周期</h3>
          <p>{{ currentTopic.duration }}天</p>
        </div>

        <div class="detail-section" v-if="currentTopic.content">
          <h3>项目内容</h3>
          <p>{{ currentTopic.content }}</p>
        </div>

        <div class="detail-section" v-if="currentTopic.expectedOutcome">
          <h3>预期成果</h3>
          <p>{{ currentTopic.expectedOutcome }}</p>
        </div>
      </div>
    </el-dialog>

    <!-- 申请详情对话框 -->
    <el-dialog
      v-model="applicationDetailVisible"
      title="申请详情"
      width="800px"
    >
      <div v-if="currentApplication" class="application-detail">
        <h2>{{ currentApplication.topicTitle }}</h2>
        <p class="detail-meta">企业: {{ currentApplication.enterprise }} | 申请时间: {{ currentApplication.applyTime }}</p>

        <el-descriptions :column="2" border>
          <el-descriptions-item label="状态">
            <el-tag :type="getApplicationStatusType(currentApplication.status)">
              {{ currentApplication.statusText }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预期投入时间">{{ currentApplication.expected_time }}小时/周</el-descriptions-item>
          <el-descriptions-item label="可开始时间">{{ currentApplication.start_date }}</el-descriptions-item>
          <el-descriptions-item label="可结束时间">{{ currentApplication.end_date }}</el-descriptions-item>
        </el-descriptions>

        <div class="detail-section">
          <h3>申请信</h3>
          <p>{{ currentApplication.cover_letter }}</p>
        </div>

        <div class="detail-section">
          <h3>研究计划</h3>
          <p>{{ currentApplication.research_plan }}</p>
        </div>

        <div class="detail-section">
          <h3>申请动机</h3>
          <p>{{ currentApplication.motivation }}</p>
        </div>

        <div class="detail-section">
          <h3>资质说明</h3>
          <p>{{ currentApplication.qualifications }}</p>
        </div>

        <div class="detail-section">
          <h3>作品集</h3>
          <a :href="currentApplication.portfolio" target="_blank">{{ currentApplication.portfolio }}</a>
        </div>

        <div class="detail-section">
          <h3>简历</h3>
          <a :href="currentApplication.resume" target="_blank">{{ currentApplication.resume }}</a>
        </div>

        <div class="detail-section" v-if="currentApplication.feedback">
          <h3>反馈意见</h3>
          <p>{{ currentApplication.feedback }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  OfficeBuilding,
  Collection,
  Calendar,
  Money,
  Plus,
  User,
  Timer,
  ChatDotRound
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import * as studentApi from '@/api/student'
import ResumeBuilder from '@/components/ResumeBuilder.vue'

// 当前激活的标签页
const activeTab = ref('topics')
const router = useRouter()

// 筛选条件
const filters = reactive({
  keyword: '',
  category: '',
  budget_min: undefined as number | undefined,
  budget_max: undefined as number | undefined,
  status: '',
  is_public: ''
})

// 申请状态筛选
const applicationStatus = ref('')

// 分页
const currentPage = ref(1)
const pageSize = ref(12)
const totalTopics = ref(0)

// 对话框状态
const applyDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const applicationDetailVisible = ref(false)
const currentTopic = ref<studentApi.Project | null>(null)
const currentApplication = ref<studentApi.Application | null>(null)

// 申请表单
const applyForm = reactive({
  coverLetter: '',
  researchPlan: '',
  motivation: '',
  qualifications: '',
  expectedTime: 10,
  startDate: '',
  endDate: '',
  portfolio: '',
  resume: ''
})

// 表单验证规则
const applyRules = {
  coverLetter: [
    { required: true, message: '请输入申请信', trigger: 'blur' }
  ],
  researchPlan: [
    { required: true, message: '请输入研究计划', trigger: 'blur' }
  ],
  portfolio: [
    { required: true, message: '请输入作品集链接', trigger: 'blur' }
  ],
  resume: [
    { required: true, message: '请输入简历链接', trigger: 'blur' }
  ],
  expectedTime: [
    { required: true, message: '请输入预期投入时间', trigger: 'blur' }
  ],
  startDate: [
    { required: true, message: '请选择可开始时间', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择可结束时间', trigger: 'change' }
  ]
}

// 课题数据
const topics = ref<studentApi.Project[]>([])
// 申请数据
const applications = ref<studentApi.Application[]>([])
// 我的项目数据
const myProjects = ref<studentApi.MyProject[]>([])
// 学习资源数据
const resources = ref<studentApi.Resource[]>([])
// 过滤后的课题列表
const filteredTopics = ref<studentApi.Project[]>([])

//const filteredTopics = computed(() => {
  //return topics.value
//})

// 过滤后的申请列表
const filteredApplications = computed(() => {
  if (!applicationStatus.value) {
    return applications.value
  }
  return applications.value.filter(app => app.status === applicationStatus.value)
})

// 获取状态类型
const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    open: 'success',
    pending: 'warning',
    closed: 'info',
    in_progress: 'primary',
    completed: 'success'
  }
  return typeMap[status] || 'info'
}

const getApplicationStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    pending: 'warning',
    accepted: 'success',
    rejected: 'danger',
    withdrawn: 'info'
  }
  return typeMap[status] || 'info'
}

const getProjectStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    ongoing: 'primary',
    completed: 'success',
    pending: 'info',
    problem: 'danger'
  }
  return typeMap[status] || 'info'
}

const getResourceType = (type: string) => {
  const typeMap: Record<string, string> = {
    tutorial: 'success',
    guide: 'primary',
    course: 'warning',
    document: 'info'
  }
  return typeMap[type] || 'info'
}

// 处理requirements数据，确保返回数组格式
const getRequirementsList = (requirements: any): string[] => {
  if (!requirements) return []
  
  if (Array.isArray(requirements)) {
    return requirements.filter(req => req && req.trim())
  }
  
  if (typeof requirements === 'string') {
    // 按换行符分割，过滤空行
    return requirements.split('\n').map(req => req.trim()).filter(req => req)
  }
  
  return []
}

// 加载课题列表
const loadProjects = async () => {
  try {
    // 如果有搜索关键词，使用搜索接口
    if (filters.keyword && filters.keyword.trim()) {
      const searchParams = {
        q: filters.keyword.trim(),
        page: currentPage.value,
        size: pageSize.value,
        category: filters.category,
        budget_min: filters.budget_min,
        budget_max: filters.budget_max
      }
      const response = await studentApi.searchProjects(searchParams)
      topics.value = (response as any).data.map((project: any) => ({
        ...project,
        enterprise: project.enterprise_id?.toString() || '未知企业',
        statusText: getStatusText(project.status),
        requirements: project.requirements ? (Array.isArray(project.requirements) ? project.requirements : project.requirements.split('\n').filter((req: string) => req.trim())) : [],
        hasApplied: checkIfApplied(project.id),
        publishTime: formatDate(project.created_at || ''),
        content: project.description,
        expectedOutcome: ''
      }))
      totalTopics.value = (response as any).total || topics.value.length
      return
    }

    // 否则使用普通列表接口
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      keyword: filters.keyword,
      category: filters.category,
      status: filters.status,
      budget_min: filters.budget_min,
      budget_max: filters.budget_max,
      is_public: filters.is_public
    }

    const response = await studentApi.getProjects(params)
    // 根据实际API返回结构：{ code, message, data: [], total, page, size, pages }
    topics.value = (response as any).data.map((project: any) => ({
      ...project,
      enterprise: project.enterprise_id?.toString() || '未知企业',
      statusText: getStatusText(project.status),
      requirements: project.requirements ? (Array.isArray(project.requirements) ? project.requirements : project.requirements.split('\n').filter((req: string) => req.trim())) : [],
      hasApplied: checkIfApplied(project.id), // 需要根据实际接口调整
      publishTime: formatDate(project.created_at || ''),
      content: project.description, // 需要根据实际接口调整
      expectedOutcome: '' // 需要根据实际接口调整
    }))
    filteredTopics.value =  topics.value
    totalTopics.value = (response as any).total || topics.value.length
  } catch (error) {
    ElMessage.error('加载课题列表失败')
  }
}

// 加载申请列表
const loadApplications = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }

    const response = await studentApi.getMyApplications(params)
    // 根据API文档，返回结构是 { code, message, data: [], total, page, size, pages }
    applications.value = (response as any).data.map((app: any) => ({
      ...app,
      topicTitle: app?.project?.title || '未知课题',
      enterprise: app?.project?.enterprise_id?.toString() || '未知企业',
      applyTime: formatDate(app.apply_date || app.created_at || ''),
      statusText: getApplicationStatusText(app.status),
      feedback: app.review_comment || '',
      start_date: formatDate(app.start_date || ''),
      end_date: formatDate(app.end_date || '')
    }))
    console.log("加载申请列表：",applications.value)
  } catch (error) {
    ElMessage.error('加载申请列表失败')
  }
}

// 提取所有已申请的项目ID
const getAppliedProjectIds = (): ( number)[] => {
  if (!applications.value || applications.value.length === 0) return []
  return applications.value.map(app => app.project_id).filter(id => id !== undefined && id !== null)
}

// 检查项目是否处于待审核中的申请
const checkIfApplied = (projectId: number): boolean => {
  if (!applications.value || applications.value.length === 0) {
    return false;
  }
  
  // 查找状态为"pending"且项目ID匹配的申请
  return applications.value.some(app => 
    app.project_id !== undefined && 
    app.project_id !== null &&
    app.project_id.toString() === projectId.toString() &&
    app.status === "pending"
  );
};

// 加载我的项目
const loadMyProjects = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }
    
    const response = await studentApi.getMyProjects(params)
    myProjects.value = (response as any).data.map((project: any) => ({
      ...project,
      statusText: getProjectStatusText(project.status),
      startDate: formatDate(project.startDate || project.start_date || '')
    }))
  } catch (error) {
    ElMessage.error('加载我的项目失败')
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    open: '开放',
    closed: '已关闭',
    in_progress: '进行中',
    completed: '已完成'
  }
  return statusMap[status] || status
}

const getApplicationStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待审核',
    accepted: '已通过',
    rejected: '已拒绝',
    withdrawn: '已撤回'
  }
  return statusMap[status] || status
}

const getProjectStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    ongoing: '进行中',
    completed: '已完成',
    pending: '待开始',
    problem: '有问题'
  }
  return statusMap[status] || status
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString()
}

// 搜索
const handleSearch = async () => {
  currentPage.value = 1
  await loadProjects()
  ElMessage.success('搜索完成')
}

// 重置筛选条件
const resetFilters = () => {
  filters.keyword = ''
  filters.category = ''
  filters.budget_min = undefined
  filters.budget_max = undefined
  filters.status = ''
  filters.is_public = ''
  currentPage.value = 1
  loadProjects()
}

// 显示申请对话框
const showApplyDialog = (topic: studentApi.Project) => {
  currentTopic.value = topic
  applyDialogVisible.value = true
  // 重置表单
  applyForm.coverLetter = ''
  applyForm.researchPlan = ''
  applyForm.motivation = ''
  applyForm.qualifications = ''
  applyForm.expectedTime = 10
  applyForm.startDate = ''
  applyForm.endDate = ''
  applyForm.portfolio = ''
  applyForm.resume = ''
}

// 显示课题详情
const showTopicDetail = async (topic: studentApi.Project) => {
  try {
    const response = await studentApi.getProjectDetail(topic.id)
    currentTopic.value = {
      ...topic,
      ...response
    }
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取课题详情失败')
  }
}

// 关闭申请对话框
const handleCloseApplyDialog = () => {
  applyDialogVisible.value = false
}

// 提交申请
const submitApplication = async () => {
  try {
    if (!currentTopic.value) return

    const requestData = {
      project_id: currentTopic.value.id,
      cover_letter: applyForm.coverLetter,
      portfolio: applyForm.portfolio,
      resume: applyForm.resume,
      motivation: applyForm.motivation,
      qualifications: applyForm.qualifications,
      research_plan: applyForm.researchPlan,
      expected_time: parseInt(applyForm.expectedTime.toString()),
      start_date: applyForm.startDate ? new Date(applyForm.startDate).toISOString() : undefined,
      end_date: applyForm.endDate ? new Date(applyForm.endDate).toISOString() : undefined
    }

    const response = await studentApi.createApplication(requestData)

    if ((response as any).code === 200) {
      ElMessage.success('申请提交成功！')
      applyDialogVisible.value = false
      // 刷新申请列表
      await loadApplications()
      //刷新课题列表
      await loadProjects()
      // 切换到申请进度标签页
      activeTab.value = 'applications'
    } else {
      ElMessage.error((response as any).message || '申请提交失败')
    }
  } catch (error) {
    ElMessage.error('申请提交失败，请重试')
  }
}

// 查看申请详情
const viewApplicationDetail = async (application: studentApi.Application) => {
  try {
    const response = await studentApi.getApplicationDetail(application.id)
    // 根据API文档，返回结构是 { code, message, data: {...}, trace_id }
    const appData = (response as any).data
    currentApplication.value = {
      ...appData,
      topicTitle: appData?.project?.title || application.topicTitle,
      enterprise: appData?.project?.enterprise_id?.toString() || application.enterprise,
      applyTime: formatDate(appData?.apply_date || appData?.created_at || ''),
      statusText: getApplicationStatusText(appData?.status || application.status),
      feedback: appData?.review_comment || application.feedback,
      start_date: formatDate(appData?.start_date || ''),
      end_date: formatDate(appData?.end_date || '')
    }
    applicationDetailVisible.value = true
  } catch (error) {
    ElMessage.error('获取申请详情失败')
  }
}

// 撤回申请
const withdrawApplication = async (application: studentApi.Application) => {
  try {
    await ElMessageBox.confirm('确定要撤回该申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await studentApi.withdrawApplication(application.id)
    
    if (response.code === 200) {
      ElMessage.success('申请撤回成功')
      await loadApplications()
      //刷新课题列表
      await loadProjects()
    } else {
      ElMessage.error(response.message || '撤回申请失败')
    }
  } catch (error: any) {
    // 用户取消了操作或其他错误
    if (error !== 'cancel') {
      // 处理具体的错误响应
      const errorMessage = error?.response?.data?.message || error?.message || '撤回申请失败';
      ElMessage.error(errorMessage);
      console.error(error);
    }
  }
}

// 查看项目详情
const viewProjectDetail = (project: studentApi.MyProject) => {
  ElMessage.info(`查看项目 ${project.title} 的详细信息`)
}

// 查看学习资源
const viewResource = (resource: studentApi.Resource) => {
  ElMessage.info(`查看学习资源 ${resource.title}`)
}

// 下载学习资源
const downloadResource = (resource: studentApi.Resource) => {
  ElMessage.success(`开始下载 ${resource.title}`)
}

// 联系企业
const contactEnterprise = (topic: any) => {
  if (!topic.creator_id) {
    ElMessage.warning('无法获取企业信息')
    return
  }
  
  // 跳转到聊天页面，并传递企业用户ID
  router.push({
    path: '/chat',
    query: {
      userId: topic.creator_id,
      userName: topic.creator?.username || topic.enterprise || '企业用户',
      topicTitle: topic.title
    }
  })
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  loadProjects()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadProjects()
}

// 初始化加载数据
onMounted(async () => {
  await loadApplications()
  await loadProjects()
  await loadMyProjects()
})
</script>

<style scoped>
.student-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-header h1 {
  color: #045108;
  margin-bottom: 8px;
}

.page-header p {
  color: #666;
  font-size: 16px;
}

.student-tabs {
  margin-bottom: 24px;
}

.filter-section {
  margin-bottom: 24px;
}

.filter-card {
  background: linear-gradient(135deg, #f8f9fa 0%, #e8f5e8 100%);
}

.filter-row {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.topics-section {
  margin-bottom: 24px;
}

.topic-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.topic-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.topic-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.topic-title {
  margin: 0;
  font-size: 18px;
  color: #045108;
  flex: 1;
  margin-right: 12px;
}

.topic-content {
  margin-bottom: 20px;
}

.topic-description {
  color: #666;
  margin-bottom: 16px;
  line-height: 1.6;
}

.topic-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
}

.topic-requirements {
  margin-bottom: 16px;
}

.topic-requirements h4 {
  margin: 0 0 8px 0;
  color: #045108;
  font-size: 14px;
}

.topic-requirements ul {
  margin: 0;
  padding-left: 20px;
  color: #666;
  font-size: 14px;
}

.topic-requirements li {
  margin-bottom: 4px;
}

.topic-actions {
  display: flex;
  gap: 12px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  margin: 40px 0;
}

.applications-section,
.projects-section,
.resources-section {
  margin-bottom: 24px;
}

.applications-card,
.projects-card,
.resources-card {
  background: white;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.topic-detail h2 {
  color: #045108;
  margin-bottom: 16px;
}

.detail-description {
  color: #666;
  margin-bottom: 24px;
  line-height: 1.6;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h3 {
  color: #045108;
  margin-bottom: 12px;
  font-size: 16px;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.requirements-list {
  p {
    margin-bottom: 8px;
    padding-left: 16px;
    position: relative;
    
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 8px;
      width: 6px;
      height: 6px;
      background-color: #409eff;
      border-radius: 50%;
    }
  }
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  
  .tag-item {
    margin: 0;
  }
}

.detail-section ul {
  margin: 0;
  padding-left: 20px;
  color: #666;
}

.detail-section li {
  margin-bottom: 4px;
}

.detail-section p {
  color: #666;
  line-height: 1.6;
  margin: 0;
}

.project-card,
.resource-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.project-card:hover,
.resource-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.project-header,
.resource-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.project-title,
.resource-title {
  margin: 0;
  font-size: 18px;
  color: #045108;
  flex: 1;
  margin-right: 12px;
}

.project-content,
.resource-content {
  margin-bottom: 20px;
}

.project-description,
.resource-description {
  color: #666;
  margin-bottom: 16px;
  line-height: 1.6;
}

.project-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-bottom: 16px;
}

.project-actions,
.resource-actions {
  display: flex;
  gap: 12px;
}

.resource-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #999;
  font-size: 14px;
}

.application-detail h2 {
  color: #045108;
  margin-bottom: 8px;
}

.detail-meta {
  color: #666;
  margin-bottom: 24px;
  font-size: 14px;
}
</style>
